package beans;


import database.DatabaseConnection;
import database.Sql;

import java.io.PrintWriter;

import java.math.BigDecimal;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.Iterator;

import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import javax.servlet.http.HttpServletResponse;

import obj.Teachers;

import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;
import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.model.RowKeySet;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

import view.FormularInterface;


public class TeachersFormularBB implements FormularInterface {
    private RichPanelFormLayout panelFormLayoutFormular;
    private RichPanelFormLayout panelFormLayoutFormularLogin;

    private static final long serialVersionUID = 1L;
    ArrayList<Teachers> listTeachers = new ArrayList<Teachers>();
    private RichTable tableTeachers;
    private String output;
    private boolean outputRendered = false;
    private BigDecimal idTeacher;
    private String name;
    private String password;
    private RichPanelGroupLayout panelGroupLayout;

    public TeachersFormularBB() {
       teacher();
    }
    public void login(ActionEvent actionEvent) {
        String url = null;
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            System.out.println("Nume" + getName() + getPassword());
            rs =
    stmt.executeQuery(" select id_prof from profesori where username= '" + getName() + "' and parola= '" +
                   getPassword() + "'");

            if (rs.next()) {
                idTeacher = rs.getBigDecimal("id_prof");
              
            }
        } catch (ClassNotFoundException ex) {
        } catch (SQLException ex) {
            System.out.println("eroare sql " + ex);
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }
        }
        if (idTeacher != null) { //  redirect to a other url
            ExternalContext ectx;
            ectx = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletResponse response;
            response = (HttpServletResponse)ectx.getResponse();
            url = "http://127.0.0.1:7101" + ectx.getRequestContextPath() + "/faces/dashboard1.jsf";
            try {
                response.sendRedirect(url);
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("Eroareee" + ex);
            }
        } else {
            System.out.println("Username or password is wrong");
            output = "Username or password is wrong !";
            outputRendered = true;
            RequestContext context = RequestContext.getCurrentInstance();
            context.addPartialTarget(panelGroupLayout);
        }

    }
    @Override
    public void insert(ActionEvent actionEvent) {
        String nume = null;
        String prenume = null;
        String email = null;
        int nr;
        for (UIComponent uiComp : panelFormLayoutFormular.getChildren()) {
            RichInputText input = (RichInputText)uiComp;
            if (uiComp.getId().equalsIgnoreCase("itNume")) {
                nume = (String)input.getValue();

            }
            if (uiComp.getId().equalsIgnoreCase("itPrenume")) {
                prenume = (String)input.getValue();
            }            
            if (uiComp.getId().equalsIgnoreCase("itEmail")) {
                email = (String)input.getValue();
            }
        }
        insert(nume, prenume, email);
    }

    @Override
    public void update(ActionEvent actionEvent) {
        String nume = null;
        String prenume = null;
        String email = null;
        String master = null;
        int nr = -1;
        Connection con = null;
        Statement stmt1 = null;
        Statement stmt2 = null;
        Statement stmt3 = null;
        PrintWriter pw = null;
        ResultSet rs = null;

        try {
            con = DatabaseConnection.getConectare();
            stmt1 = con.createStatement();


            for (UIComponent uiComp : panelFormLayoutFormular.getChildren()) {
                RichInputText input = (RichInputText)uiComp;
                if (uiComp.getId().equalsIgnoreCase("itNr")) {
                    if (input.getValue() != null) {
                        nr = (Integer)input.getValue();
                    }

                }
                if (uiComp.getId().equalsIgnoreCase("itNume")) {
                    nume = (String)input.getValue();

                }
                if (uiComp.getId().equalsIgnoreCase("itPrenume")) {
                    prenume = (String)input.getValue();
                }               
                if (uiComp.getId().equalsIgnoreCase("itEmail")) {
                    email = (String)input.getValue();
                }
            }
            String sqlSelect = " select * from profesori where id_prof=" + nr;
            String sqlUpdate =
                " update profesori set  nume='" + nume + "', prenume='" + prenume + "',email='" + email + "'" + " where id_prof=" + nr;

            rs = stmt1.executeQuery(sqlSelect);

            if (rs.next()) {
                stmt2 = con.createStatement();
                stmt2.executeUpdate(sqlUpdate);
                System.out.println("Update" + sqlUpdate);
            } else {

            }

        } catch (ClassNotFoundException ex) {

        } catch (SQLException ex) {
            System.out.println("eroare sql " + ex);
        } finally {

            try {
                if (stmt1 != null)
                    stmt1.close();
                if (stmt2 != null)
                    stmt2.close();
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {
            }
        }
    }

    public void insert(String nume, String prenume, String email) {
        if (nume != null && prenume != null) {
            Connection con = null;
            Statement stmt1 = null;
            try {
                con = DatabaseConnection.getConectare();
                stmt1 = con.createStatement();
                int nr = Sql.generateID("PROFESORI", "ID_PROF");
                String sqlInsert =
                    " insert into profesori (id_prof,username,nume,prenume,email,parola) values (" + nr +
                    ",'" + nume + prenume + "'," + "'" + nume + "','" + prenume + "','" + email + "'," +
                    "'a')";
                int executeUpdate = stmt1.executeUpdate(sqlInsert);
            } catch (ClassNotFoundException ex) {

            } catch (SQLException ex) {
                System.out.println("eroare sql " + ex);
            } finally {

                try {
                    if (stmt1 != null)
                        stmt1.close();

                } catch (SQLException ex) {
                }
            }
        }
    }
    
    public void teacher() {
        listTeachers.clear();
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            rs =
    stmt.executeQuery(" select id_prof, nume,  prenume, email from profesori ");
            while (rs.next()) {
                BigDecimal id_prof = rs.getBigDecimal("id_prof");
                System.out.println("AM inrreg " + id_prof);
                String nume = rs.getString("nume");             
                String prenume = rs.getString("prenume");
                String email = rs.getString("email");
                Teachers s = new Teachers();
                s.setProf_id(id_prof);
                s.setNume(nume);               
                s.setPrenume(prenume);   
                s.setEmail(email);
                listTeachers.add(s);
            }
        } catch (ClassNotFoundException ex) {
        } catch (SQLException ex) {
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }
        }
    }
    public void selectionTable(SelectionEvent selectionEvent) {
        RichTable _mainTable = (RichTable)selectionEvent.getSource();
        Object _selectedrowdata = _mainTable.getSelectedRowData();
        Teachers s = (Teachers)_selectedrowdata;
        name = s.getNume() + "" + s.getPrenume();
        setIdTeacher(s.getProf_id());     
        RequestContext context = RequestContext.getCurrentInstance();
        context.addPartialTarget(panelFormLayoutFormularLogin);
    }

    @Override
    public void refreshTable(ActionEvent actionEvent) {
        teacher();
        AdfFacesContext context = AdfFacesContext.getCurrentInstance();
        context.addPartialTarget(tableTeachers);
    }
    //method referenced from the af:dropTarget

    public DnDAction dropHandler(DropEvent dropEvent) {
        //access the drag source, the table to read the rowKey
        ////representing the row
        RichTable table = (RichTable)dropEvent.getDragComponent();
        Transferable t = dropEvent.getTransferable();
        DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class, "rowcopy");
        RowKeySet rks = t.getData(df);
        Iterator iter = rks.iterator();
        //sample is set up for single row drag and drop
        if (iter.hasNext()) {
            //get next selected row key
            Integer key = (Integer)iter.next();
            table.setRowKey(key);
            //get handle to drop component
            RichPanelFormLayout panelFormLayout = (RichPanelFormLayout)dropEvent.getDropComponent();
            //JUCtrlHierNodeBinding is the object in ADF that represents //a row in a table or a node in a tree. The object wraps the
            //actual table row object, which in the case of ADF BC is

            Object rowBinding = (Object)table.getRowData();
            Teachers teacherDropRow = (Teachers)rowBinding;
            //the row that is actually dragged from the ADF Faces table

            //update current row in form if the table row is not null
            if (teacherDropRow != null) {
                //to evaluate and update the manager Id field, we need to create
                //and store a handle to it. The bean is in request (or backing
                //bean scop, so no overhead)

                //search all panelFormLayout component children for the
                //update more than 2 fields

                for (UIComponent uiComp : panelFormLayout.getChildren()) {

                    if (uiComp.getId().equalsIgnoreCase("itNr")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(teacherDropRow.getProf_id());
                    }

                    if (uiComp.getId().equalsIgnoreCase("itNume")) {
                        System.out.println("Randul selectat este=" + uiComp.getClientId());
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(teacherDropRow.getNume());

                    }
                    if (uiComp.getId().equalsIgnoreCase("itPrenume")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(teacherDropRow.getPrenume());
                    }
                   
                    if (uiComp.getId().equalsIgnoreCase("itEmail")) {
                        ((RichInputText)uiComp).resetValue();
                        ((RichInputText)uiComp).setValue(teacherDropRow.getEmail());
                    }
                }

            }
            FacesContext fctx = FacesContext.getCurrentInstance();
            ExtendedRenderKitService erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
            erks.addScript(fctx, "AdfPage.PAGE.clearAllMessages();");
            return DnDAction.COPY;
        }
        //no drag and drop happened
        {
            return DnDAction.NONE;
        }
    }

    public void setPanelFormLayoutFormular(RichPanelFormLayout panelFormLayoutFormular) {
        this.panelFormLayoutFormular = panelFormLayoutFormular;
    }

    public RichPanelFormLayout getPanelFormLayoutFormular() {
        return panelFormLayoutFormular;
    }


    public void setPanelFormLayoutFormularLogin(RichPanelFormLayout panelFormLayoutFormularLogin) {
        this.panelFormLayoutFormularLogin = panelFormLayoutFormularLogin;
    }

    public RichPanelFormLayout getPanelFormLayoutFormularLogin() {
        return panelFormLayoutFormularLogin;
    }



    public void setTableTeachers(RichTable tableTeachers) {
        this.tableTeachers = tableTeachers;
    }

    public RichTable getTableTeachers() {
        return tableTeachers;
    }

    public void setOutput(String output) {
        this.output = output;
    }

    public String getOutput() {
        return output;
    }

    public void setOutputRendered(boolean outputRendered) {
        this.outputRendered = outputRendered;
    }

    public boolean isOutputRendered() {
        return outputRendered;
    }


    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setPanelGroupLayout(RichPanelGroupLayout panelGroupLayout) {
        this.panelGroupLayout = panelGroupLayout;
    }

    public RichPanelGroupLayout getPanelGroupLayout() {
        return panelGroupLayout;
    }

    public void setListTeachers(ArrayList<Teachers> listTeachers) {
        this.listTeachers = listTeachers;
    }

    public ArrayList<Teachers> getListTeachers() {
        return listTeachers;
    }

    public void setIdTeacher(BigDecimal idTeacher) {
        this.idTeacher = idTeacher;
    }

    public BigDecimal getIdTeacher() {
        return idTeacher;
    }
}
